package xin.sunzy.ssms.realm;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import xin.sunzy.ssms.entity.po.Permission;
import xin.sunzy.ssms.entity.po.Role;
import xin.sunzy.ssms.entity.po.User;
import xin.sunzy.ssms.service.intf.IUserService;

public class MyRealm extends AuthorizingRealm {
    private final Logger LOG = LoggerFactory.getLogger(MyRealm.class);

    @Autowired
    private IUserService userService;

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

		System.out.println("MyRealm   doGetAuthenticationInfo ********");
		
		//从token中获取username
        try {
            String username = ((UsernamePasswordToken)token).getUsername();
            User user = userService.findByUsername(username);
            if(user==null){
                LOG.error("用户不存在异常。。。");
            }
            ByteSource credentialsSalt = ByteSource.Util.bytes(user.getCredentialsSalt());
            //SimpleAuthenticationInfo(Object principal, Object credentials, String realmName)
            //principal:从数据库中获取的用户实体或者username，credentials：从数据库中获取的密码，realmName：realm的名字
            AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user,user.getPassword(),credentialsSalt,getName());
            return authenticationInfo;
        } catch (Exception e) {
            LOG.error("登陆认证异常******");
            return null;
        }
	}
	
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        System.out.println("MyRealm，开始授权，doGetAuthorizationInfo**********");
        /*User user = (User) principalCollection.fromRealm(getName()).iterator().next();*/
        User user = (User) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        for(Role role:user.getRoleList()){
            authorizationInfo.addRole(role.getRoleName());
            for (Permission p : role.getPermissionList()){
                authorizationInfo.addStringPermission(p.getPermission());
                authorizationInfo.addStringPermission(p.getOpsUrl());
            }
        }

        return authorizationInfo;
    }
}
